<?php
namespace App\Controller;

use Think\Upload;

class UeditorController extends BaseController
{
    public $L;
    public function __construct()
    {
        parent::__construct();
    }

	public function config()
	{
		$config = include(APP_PATH.'Common/Conf/ueditor.php');
		$action = $_GET['action'];
		switch ($action) {
			case 'config':
				$result =  json_encode($config);
				break;
			case 'uploadimage':
			case 'uploadscrawl':
			case 'uploadvideo':
			case 'uploadfile':
				$result = $this->upload();
				break;
			case 'listimage':
				$result = $this->ls();
				break;
			case 'listfile':
				$result = $this->ls();
				break;
			case 'catchimage':
				//抓取远程文件
				//$result = include("action_crawler.php");
				break;
			default:
				$result = json_encode(array(
					'state'=> '请求地址出错'
				));
				break;
		}

		/* 输出结果 */
		if (isset($_GET["callback"])) {
			if (preg_match("/^[\w_]+$/", $_GET["callback"])) {
				echo htmlspecialchars($_GET["callback"]) . '(' . $result . ')';
			} else {
				echo json_encode(array(
					'state'=> 'callback参数不合法'
				));
			}
		} else {
			echo $result;
		}
    }

	public function upload()
	{
		$file = current($_FILES);
		if(!$file) {
			echo json_encode(array('state'=> '无文件上传'));exit;
		}

		$config = array(
			'rootPath' => './upload',
			'savePath' => '/ueditor/',
			'saveName' =>  md5_file($file['tmp_name']),
			'exts' => array(),
			'autoSub' => true,
			'subName' => array('date', 'Ymd'),
		);
		$upload = new Upload($config);
		$up_info = $upload->uploadOne($file);
		if($up_info === false){
			echo json_encode(array('state'=> $upload->getError()));exit;
		}
		$url = 'http://'.$_SERVER['HTTP_HOST'].'/upload'.$up_info['savepath'].$up_info['savename'];

		$return = array(
		 	"state" => "SUCCESS",          //上传状态，上传成功时必须返回"SUCCESS"
		 	"url" => $url,            //返回的地址
		 	"title" => $up_info['savename'],          //新文件名
		 	"original" => $up_info['name'],       //原始文件名
		 	"type" => $up_info['type'],            //文件类型
			"size" => $up_info['size'],           //文件大小
		);

		/* 返回数据 */
		echo json_encode($return); exit;



		/**
		 * 上传附件和上传视频
		 * User: Jinqn
		 * Date: 14-04-09
		 * Time: 上午10:17
		 */
		include "Uploader.class.php";

		/* 上传配置 */
		$base64 = "upload";
		switch (htmlspecialchars($_GET['action'])) {
			case 'uploadimage':
				$config = array(
					"pathFormat" => $CONFIG['imagePathFormat'],
					"maxSize" => $CONFIG['imageMaxSize'],
					"allowFiles" => $CONFIG['imageAllowFiles']
				);
				$fieldName = $CONFIG['imageFieldName'];
				break;
			case 'uploadscrawl':
				$config = array(
					"pathFormat" => $CONFIG['scrawlPathFormat'],
					"maxSize" => $CONFIG['scrawlMaxSize'],
					"allowFiles" => $CONFIG['scrawlAllowFiles'],
					"oriName" => "scrawl.png"
				);
				$fieldName = $CONFIG['scrawlFieldName'];
				$base64 = "base64";
				break;
			case 'uploadvideo':
				$config = array(
					"pathFormat" => $CONFIG['videoPathFormat'],
					"maxSize" => $CONFIG['videoMaxSize'],
					"allowFiles" => $CONFIG['videoAllowFiles']
				);
				$fieldName = $CONFIG['videoFieldName'];
				break;
			case 'uploadfile':
			default:
				$config = array(
					"pathFormat" => $CONFIG['filePathFormat'],
					"maxSize" => $CONFIG['fileMaxSize'],
					"allowFiles" => $CONFIG['fileAllowFiles']
				);
				$fieldName = $CONFIG['fileFieldName'];
				break;
		}

		/* 生成上传实例对象并完成上传 */
		$up = new Uploader($fieldName, $config, $base64);

		/**
		 * 得到上传文件所对应的各个参数,数组结构
		 * array(
		 *     "state" => "",          //上传状态，上传成功时必须返回"SUCCESS"
		 *     "url" => "",            //返回的地址
		 *     "title" => "",          //新文件名
		 *     "original" => "",       //原始文件名
		 *     "type" => ""            //文件类型
		 *     "size" => "",           //文件大小
		 * )
		 */

		/* 返回数据 */
		return json_encode($up->getFileInfo());
	}
	//上传文件
	public function ls()
	{
		echo 'list files';
		exit;
		include "Uploader.class.php";

		/* 判断类型 */
		switch ($_GET['action']) {
			/* 列出文件 */
			case 'listfile':
				$allowFiles = $CONFIG['fileManagerAllowFiles'];
				$listSize = $CONFIG['fileManagerListSize'];
				$path = $CONFIG['fileManagerListPath'];
				break;
			/* 列出图片 */
			case 'listimage':
			default:
				$allowFiles = $CONFIG['imageManagerAllowFiles'];
				$listSize = $CONFIG['imageManagerListSize'];
				$path = $CONFIG['imageManagerListPath'];
		}
		$allowFiles = substr(str_replace(".", "|", join("", $allowFiles)), 1);

		/* 获取参数 */
		$size = isset($_GET['size']) ? htmlspecialchars($_GET['size']) : $listSize;
		$start = isset($_GET['start']) ? htmlspecialchars($_GET['start']) : 0;
		$end = $start + $size;

		/* 获取文件列表 */
		$path = $_SERVER['DOCUMENT_ROOT'] . (substr($path, 0, 1) == "/" ? "" : "/") . $path;
		$files = getfiles($path, $allowFiles);
		if (!count($files)) {
			return json_encode(array(
				"state" => "no match file",
				"list" => array(),
				"start" => $start,
				"total" => count($files)
			));
		}

		/* 获取指定范围的列表 */
		$len = count($files);
		for ($i = min($end, $len) - 1, $list = array(); $i < $len && $i >= 0 && $i >= $start; $i--) {
			$list[] = $files[$i];
		}

		/* 返回数据 */
		$result = json_encode(array(
			"state" => "SUCCESS",
			"list" => $list,
			"start" => $start,
			"total" => count($files)
		));

		return $result;


		/**
		 * 遍历获取目录下的指定类型的文件
		 * @param $path
		 * @param array $files
		 * @return array
		 */
		function getfiles($path, $allowFiles, &$files = array())
		{
			if (!is_dir($path)) return null;
			if (substr($path, strlen($path) - 1) != '/') $path .= '/';
			$handle = opendir($path);
			while (false !== ($file = readdir($handle))) {
				if ($file != '.' && $file != '..') {
					$path2 = $path . $file;
					if (is_dir($path2)) {
						getfiles($path2, $allowFiles, $files);
					} else {
						if (preg_match("/\.(" . $allowFiles . ")$/i", $file)) {
							$files[] = array(
								'url' => substr($path2, strlen($_SERVER['DOCUMENT_ROOT'])),
								'mtime' => filemtime($path2)
							);
						}
					}
				}
			}
			return $files;
		}
	}
}